package cn.ffcs.uec.outStaffEncPunishTalentInputApply.component;

import java.io.FileInputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lombok.Getter;
import lombok.Setter;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.util.media.Media;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffEncPunishTalentInputApply.component.bean.UecOutStaffPunishInputListboxBean;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecPunishManager;
import cn.ffcs.uec.staff.model.UecPunish;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.FileUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import cn.ffcs.uom.common.vo.PageInfo;
import cn.ffcs.uom.common.zul.PubUtil;

/**
 * 外包人员惩罚信息批量导入Ext
 * @author liuxiaodong
 *
 */
@Controller
@Scope("prototype")
public class UecOutStaffPunishInputListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -8459412569371510940L;

	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	private UecOutStaffPunishInputListboxBean bean = new UecOutStaffPunishInputListboxBean();
	/**
	 * 人员处罚情况实体
	 */
	private UecPunish uecPunish;

	/**
	 * 上传文件
	 */
	private Media media;

	/**
	 * 存放上传数据
	 */
	private List<UecPunish> uecPunishs = new ArrayList<UecPunish>();

	private static final int TOTAL_COLUMN = 8;

	private UecPunishManager uecPunishManager = (UecPunishManager) ApplicationContextUtil
			.getBean("uecPunishManager");

	public static final String UEC_OUT_STAFF_PUNISH_INPUT_LISTBOX_EXT_ZUL = "/pages_nmg/outStaffEncPunishTalentInputApply/comp/uecOutstaffPunishInput_listbox_ext.zul";

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutStaffPunishInputListboxExt() {
		Executions.createComponents(UEC_OUT_STAFF_PUNISH_INPUT_LISTBOX_EXT_ZUL,
				this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.bandListbox();
		this.setButtonValid(false, false, false, false, false, false);
		this.setButtonVisible(false, false, false, false);
	}
	
	
	
	/**
	 * 人员信息查询按钮
	 * 
	 * @throws Exception
	 */
	public void onQuery() throws Exception {

		clearVariable();
		if (!StrUtil.isNullOrEmpty(bean.getCondition().getSelectedItem().getValue())
				&& !StrUtil.isNullOrEmpty(bean.getConditionValue().getValue())) {
			Listbox listbox = bean.getCondition();
			String listboxStr = (String) listbox.getSelectedItem().getValue();
			int listboxId = Integer.parseInt(listboxStr);
			uecOutStaffInfo = UecOutStaffInfo.newInstance();
			switch (listboxId) {
			case 0:
				uecOutStaffInfo.setPsnName(bean.getConditionValue().getValue());
				break;
			case 1:
				uecOutStaffInfo.setPsnCode(bean.getConditionValue().getValue());
				break;
			case 2:
				uecOutStaffInfo.setIdNum(bean.getConditionValue().getValue());
				break;
			default:
				break;
			}
		}
		outStaffList();
	}
	
	/**
	 * 员工列表
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void outStaffList() throws SuspendNotAllowedException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "outStaffList");
		map.put("qryUecOutStaffInfo", uecOutStaffInfo);
		Window window = (Window) Executions.createComponents(UecOutStaffConstants.UEC_OUT_STAFF_LIST_ZUL, this, map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					uecOutStaffInfo = (UecOutStaffInfo) event.getData();
					
					if (null != uecOutStaffInfo) {
						uecPunish = new UecPunish();
						if (!StrUtil.isNullOrEmpty(uecOutStaffInfo.getPkPsnMsg())
								&& !StrUtil.isNullOrEmpty(uecOutStaffInfo.getOutStaffId())) {
							uecPunish.setPkPsndoc(uecOutStaffInfo.getPkPsnMsg());
							setButtonValid(true, true, true, false, false, false);
						} else {
							uecPunish.setStaffId(uecOutStaffInfo.getOutStaffId());
							setButtonValid(true, true, true, true, true, true);
						}
						onQueryUecPunish();
					}
				}
			}
		});
	}

	/**
	 * 选择一条记录
	 * 
	 * @throws Exception
	 */
	public void onSelectUecOutStaffPunishInputList() throws Exception {
		if (this.bean.getUecOutStaffPunishInputListbox().getSelectedCount() > 0) {
			uecPunish = (UecPunish) bean.getUecOutStaffPunishInputListbox()
					.getSelectedItem().getValue();
		}
	}



	/**
	 * 设置按钮 可用
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canDownload, boolean canUpload,
			boolean canView, boolean canAdd, boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);

		this.bean.getDownloadButton().setDisabled(!canDownload);
		this.bean.getUploadButton().setDisabled(!canUpload);
	}
	
	private void setButtonVisible(boolean canView, boolean canAdd, boolean canEdit, boolean candel) {
		this.bean.getViewButton().setVisible(canView);
		this.bean.getAddButton().setVisible(canAdd);
		this.bean.getEditButton().setVisible(canEdit);
		this.bean.getDelButton().setVisible(candel);
	}

	/**
	 * 查询人员惩罚信息
	 */
	public void onQueryUecPunish() {
		this.bean.getUecOutStaffPunishInputListboxPaging().setActivePage(0);
		this.onQueryUecPunishList();
	}

	/**
	 * 重置按钮
	 */
	public void onReset() {
		cn.ffcs.uom.common.util.PubUtil.clearComponent(this);
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onViewUecPunish() throws Exception, InterruptedException {
		openUecEditWin("view");
	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecPunish() throws Exception {
		openUecEditWin("add");
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecPunish() throws Exception, InterruptedException {
		openUecEditWin("edit");
	}

	/**
	 * 
	 * @param opType
	 */
	private void openUecEditWin(String opType) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", opType);
		if ("view".equals(opType) || "edit".equals(opType)) {
			if (null != uecPunish) {
				map.put("uecPunish", uecPunish);
			} else {
				ZkUtil.showError("请选择一条记录！", "提示信息");
				return;
			}
		} else if ("add".equals(opType)) {
			map.put("uecOutStaffInfo", uecOutStaffInfo);
		}
		Window window = (Window) Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_PUNISH_EDIT_ZUL, this, map);
		try {
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecPunish = (UecPunish) event.getData();
						onQueryUecPunishList();
					}
				}
			});
		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除按钮
	 */
	public void onDelUecPunish() {
		if (this.uecPunish != null && uecOutStaffInfo != null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecPunish.removeOnly();
						PubUtil.reDisplayListbox(bean.getUecOutStaffPunishInputListbox(),
								uecPunish, "del");
						uecPunish = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选择你要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 翻页
	 */
	public void onUecPunishListboxPaging() {
		this.onQueryUecPunishList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecPunish = null;
	}

	/**
	 * 查询
	 */
	public void onQueryUecPunishList() {
		if (null != uecPunish) {
			PageInfo pageInfo = uecPunishManager.queryPageInfoByUecPunish(
					uecPunish, this.bean.getUecOutStaffPunishInputListboxPaging()
							.getActivePage() + 1, this.bean
							.getUecOutStaffPunishInputListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecOutStaffPunishInputListbox().setModel(list);
			this.bean.getUecOutStaffPunishInputListboxPaging().setTotalSize(
					pageInfo.getTotalCount());
		}
	}

	/**
	 * 下载模版
	 */
	@SuppressWarnings("deprecation")
	public void onDownloadTemplate() {
		try {
			String charset = "UTF-8";
			// 服务器文件名
			String fileName = "uecOutStaffPunish_template.xls";
			// 编码后文件名
			String encodedName = null;
			encodedName = URLEncoder.encode(fileName, charset);
			// 将空格替换为+号
			encodedName = encodedName.replace("%20", "+");
			HttpServletRequest httpRequest = (HttpServletRequest) Executions
					.getCurrent().getNativeRequest();
			// 解决ie6 bug 或者是火狐浏览器
			if (encodedName.length() > 150 || Servlets.isGecko(httpRequest)
					|| Servlets.isGecko3(httpRequest)) {
				encodedName = new String(fileName.getBytes(charset),
						"ISO8859-1");
			}
			Filedownload.save(
					new FileInputStream(httpRequest
							.getRealPath("/pages_nmg/uec_outStaff/doc/"
									+ fileName)), "application/octet-stream",
					encodedName);
		} catch (Exception e) {
			ZkUtil.showError("下载员工奖励信息导入模版失败。", "系统提示");
		}
	}

	/**
	 * 文件上传 导入员工
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onUpload$uploadButton(final ForwardEvent forwardEvent)
			throws Exception {

		Messagebox.show("确认批量导入文件？导入后将直接发起流程！", "输入确认", Messagebox.OK
				| Messagebox.CANCEL, Messagebox.QUESTION, new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (((Integer) event.getData()).intValue() == Messagebox.OK) {
					bean.getUecOutStaffPunishInputListbox().clearSelection();

					media = ((UploadEvent) forwardEvent.getOrigin()).getMedia();
					if (null == media) {
						ZkUtil.showError("请选择要上传的文件!", "系统提示");
						return;
					}
					String fileName = media.getName();
					if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
						// readsUpLoadFile();
					} else {
						ZkUtil.showError("导入的文件必须是以.xls或.xlsx结尾的EXCEL文件!",
								"系统提示");
						return;
					}
					String[][] objArray = FileUtil.readExcel(media, 1, 1);
					if (objArray == null || objArray.length == 0) {
						ZkUtil.showError("导入文件没有数据！", "错误信息");
						return;
					}
					setDataToRows(objArray, fileName);
				} else {
					return;
				}
			}
		});

	}

	private void setDataToRows(String[][] data, String fileName) throws Exception {

		uecPunishs.clear();
		String[] row = null;
		boolean isUpload = true;
		for (int i = 0; i < data.length; i++) {
			row = data[i];
			if (row.length < TOTAL_COLUMN) {
				ZkUtil.showError("导入文件数据不全！", "错误信息");
				return;
			}

			UecPunish uecPunish = UecPunish.newInstance();
			for (int j = 0; j < TOTAL_COLUMN; j++) {

				switch (j) {
				// 惩罚类型
				case 0:
					if (null == data[i][j]) {
						ZkUtil.showError("惩罚类型为空！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setPunishType(data[i][j]);
					break;
				// 惩罚机构
				case 1:
					if (null == data[i][j]) {
						ZkUtil.showError("惩罚机构为空！", "错误提示");
						isUpload = false;
						return;
					}

					uecPunish.setPunishOrg(data[i][j]);
					break;
				// 惩罚事由
				case 2:
					if (null == data[i][j]) {
						ZkUtil.showError("惩罚事由为空！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setPunishMatter(data[i][j]);
					break;
				// 处罚级别
				case 3:
					if (null == data[i][j]) {
						ZkUtil.showError("处罚级别为空！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setGlbdef4(data[i][j]);
					break;
				// 惩罚措施
				case 4:
					if (null == data[i][j]) {
						ZkUtil.showError("惩罚措施为空！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setPunishMeas(data[i][j]);
					break;
				case 5:
					if (null == data[i][j]) {
						ZkUtil.showError("惩罚时间为空！", "错误提示");
						isUpload = false;
						return;
					}
					try {
						new SimpleDateFormat("yyyy-MM-dd").parse(data[i][j]);
					} catch (ParseException e) {
						e.printStackTrace();
						ZkUtil.showError("惩罚时间格式不正确！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setPunishDate(data[i][j]);
					break;
				// 撤销处分时间
				case 6:
					if (null == data[i][j]) {
						ZkUtil.showError("撤销处分时间为空！", "错误提示");
						isUpload = false;
						return;
					}
					try {
						new SimpleDateFormat("yyyy-MM-dd").parse(data[i][j]);
					} catch (ParseException e) {
						e.printStackTrace();
						ZkUtil.showError("撤销处分时间格式不正确！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setGlbdef2(data[i][j]);
					break;
				// 撤销处分文件
				case 7:
					if (null == data[i][j]) {
						ZkUtil.showError("撤销处分文件为空！", "错误提示");
						isUpload = false;
						return;
					}
					uecPunish.setGlbdef3(data[i][j]);
					break;
				default:
					break;
				}

			}
			if (!isUpload) {
				return;
			}

			uecPunish.setStaffId(uecOutStaffInfo.getOutStaffId());
			if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
				ZkUtil.showError("当前用户不存在！", "错误提示");
				return;
			}

			uecPunish.setCreator(PlatformUtil.getCurrentUser().getScreenName());
			uecPunish.setCreationtime(new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss").format(new Date()));
			uecPunish.setPkOrg(uecOutStaffInfo.getPkHrorg());
			uecPunish.setDr(0L);
			uecPunish.setLastflag("Y");

			uecPunishs.add(uecPunish);
		}

		if (null != uecPunishs) {
			ListModel list = new BindingListModelList(uecPunishs, true);
			this.bean.getUecOutStaffPunishInputListbox().setModel(list);
			this.bean.getUecOutStaffPunishInputListboxPaging().setTotalSize(
					uecPunishs.size());

			for (UecPunish uecPunish : uecPunishs) {

				uecPunish.addOnly();

				String startFlowJson = "{"
						+ "formTheme: '盟市人员惩罚流程',"
						+ " formContent: '惩罚人员:wangyiren',"
						+ " procDefId: 'outStaffPunishEdit:1:7544019d30414974afd4f2d514d481b0',"
						+ " urgent: '1'," + " atiActCategoryId: '21',"
						+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_PUNISH_EDIT
						+ "'," + " primaryId: " + uecPunish.getPunishId() + "}";
				 String procInstId =
				 ApprovalUtil.startApproval(startFlowJson);

				// 第一审批人如果是发起人直接到人力审批环节
				 ApprovalUtil.isCurrentAssignNames(procInstId);

			}
		}

		ZkUtil.showInformation("惩罚申请流程批量发起", "温馨提示");
	}
	
	
	/**
	 * 绑定下拉框
	 */
	public void bandListbox() {
		// 绑定下拉框
		List<NodeVo> nodeVoList = new ArrayList<NodeVo>();
		String[][] option = { { "0", "人员姓名" }, { "1", "人员编码" }, { "2", "证件号码" } };
		for (int i = 0; i < option.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(option[i][j]);
				nodeVo.setName(option[i][j + 1]);
			}
			nodeVoList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getCondition(), nodeVoList);

	}

}
